package com.employ.admin.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.employ.admin.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")

    private String port;

    private static final String ip = "http://localhost";

    /**
     * 上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {
//获取源文件的名称
        String originalFileName = file.getOriginalFilename();
//        为避免图片重复覆盖，定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();//生成一串不重复的字符串
//        获取上传的路径
        String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/" + flag + originalFileName;
        // 把文件写入到上传的路径

        FileUtil.writeBytes(file.getBytes(), rootFilePath);
//        返回结果url
        return Result.success(ip + ":" + port + "/files/" + flag);
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;//新建一个输出流对象
        //定义文件上传的根路径
        String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/";
        //获取所有的文件名称
        List<String> fileNames = FileUtil.listFileNames(basePath);
        //找到跟参数一致的文件(说明可以下载)
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {

            if (StrUtil.isNotEmpty(fileName)){//
                response.addHeader("Content-disposion","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);//获取文件的路径读取文件的字节流
                os = response.getOutputStream();//通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }

        }catch (Exception e){

            System.out.println("文件下载失败");
        }

    }
}
